﻿using AutoMapper;
using Common.Damin;
using Common.Infrastructrue.Interface;
using Common.Service;
using MediatR;
using RabitPart.WritedPartApi.Application.Comman.RBACfile;
using System.Transactions;

namespace RabitPart.WritedPartApi.Application.CommanHandel.RBACfile
{
    public class RBACPermCreateCommanHandel : IRequestHandler<RBACPermCreateComman, ApiResult>
    {
        private readonly ISys_permsResponstity permRE; 
        private readonly IMapper _mapper;
        private readonly ILogger<RBACPermCreateCommanHandel> logger;
        public RBACPermCreateCommanHandel(ISys_permsResponstity permRE, IMapper mapper, ILogger<RBACPermCreateCommanHandel> logger)
        { 
            _mapper = mapper; 
            this.permRE = permRE;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(RBACPermCreateComman request, CancellationToken cancellationToken)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    var permss = _mapper.Map<Perms>(request);
                    permss.CreateDate = DateTime.Now;
                    permss.CreateOperatorName = "权限添加";
                    await permRE.InsertAsync(permss);
                    //提交事务
                    scope.Complete();
                    return ApiResult.Success(StatusCodeEnum.Ok);
                }
                finally
                {
                    //事务回滚
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.LogError("添加用户异常" + ex.Message);
                return await Task.FromResult(ApiResult.Fail(ex.Message, StatusCodeEnum.Fail));
            }
        }

    }
}
